import numpy as np
import matplotlib.pyplot as plt

# 1.数据集的输入
data = [[0.8,1.0],[1.7,0.9],[2.7,2.4],[3.2,2.9],[3.7,2.8],[4.2,3.8],[4.2,2.7]]
data = np.array(data)
#将特征与标签分离
x_data = data[:,0]
y_data = data[:,1]

# 2. 前向计算
#y = wx + b
w = 1
b = 0
y_bar = w * x_data + b

# 3.单点误差
e_bar = y_data - y_bar
print(e_bar)

# 4.均方误差
e_pre = np.mean(e_bar**2)
print(f"均方误差：{e_pre}")

# 5.绘制图像
fig = plt.figure(figsize=(10,5))
ax1 = fig.add_subplot(1,2,1)
ax2 = fig.add_subplot(1,2,2)

#绘制第一个图像
"""
1.限制x,y的范围,设置标签
2.绘制数据集散点
3.绘制直线
"""
ax1.set_xlim(0,5)
ax1.set_ylim(0,6)
ax1.set_xlabel('x')
ax1.set_ylabel('y')

ax1.scatter(x_data,y_data,color='b')

y1 = w*0+b
y2 = w*5+b
ax1.plot([0,5],[y1,y2],color='r',linewidth=3)

#绘制第二个图像
ax2.set_xlim(0,3)
ax2.set_ylim(0,20)
w_values = np.linspace(0,3,100)
e_values = [np.mean((y_data-(w_value * x_data+b))**2) for w_value in w_values]
ax2.plot(w_values,e_values,color='g',linewidth=3)
ax2.plot(w,e_pre,marker="o",color='b',linewidth=3)


plt.show()




